package com.zzyl.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.entity.Visit;
import com.zzyl.mapper.CustomerUserMapper;
import com.zzyl.mapper.NursingProjectMapper;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.service.CustomerUserService;
import com.zzyl.service.WeChatService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.LoginVo;
import com.zzyl.vo.NursingProjectVo;
import com.zzyl.vo.TimeCountVo;
import com.zzyl.vo.VisitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description CustomerUserServiceImpl
 * @Author luohai
 * @Date 2024-10-20
 */
@Service
public class CustomerUserServiceImpl implements CustomerUserService {
    @Autowired
    private CustomerUserMapper customerUserMapper;

    @Autowired
    private WeChatService weChatService;

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private NursingProjectMapper nursingProjectMapper;

    //用于后面的登陆人名称拼接
    static ArrayList DEFAULT_NICKNAME_PREFIX = Lists.newArrayList(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );
    /**
     * C端用户登录--微信登录
     * @param  userLoginRequestDto 用户登录信息
     * @return 登录结果
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.远程调用根据登录授权码（userLoginRequestDto.getCode()）微信授权登录接口获取openId
        String openId = weChatService.getOpenId(userLoginRequestDto.getCode());
        //2.调用memberMapper根据openId查找member用用信息对象
        Member member=customerUserMapper.searchUserByOpenId(openId);
        //3.判断用户信息是否为空，为空创建Member用户对象，封装openid
        if (member == null){
            member=new Member();
            member.setOpenId(openId);
        }
        //4.远程调用根据手机号授权码（userLoginRequestDto.getPhoneCode()）微信获取手机号接口
        String phoneNumber = weChatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        //5.插入或更新
        if (member.getId()!=null && !member.getPhone().equals(phoneNumber)){
            //5.1 判断用户id不为空，并且获取的手机号与数据库查询到手机号不一致，封装最新的手机号再更新
            member.setPhone(phoneNumber);
            customerUserMapper.update(member);
        }else if (member.getId()==null){
            //5.2 判断用户id为空进行插入操作
            //封装昵称
            String name = DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * DEFAULT_NICKNAME_PREFIX.size())) + phoneNumber.substring(7);
            member.setName(name);
            //封装手机号
            member.setPhone(phoneNumber);
            //插入操作
            customerUserMapper.save(member);
        }

        //6.生成jwt令牌token
        //定义载荷
        Map<String,Object> claims=new HashMap<>();
        claims.put(Constants.JWT_USERID,member.getId());
        claims.put(Constants.JWT_USERNAME,member.getName());
        //生成token
        String token = JwtUtil.createJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(),
                jwtTokenManagerProperties.getTtl(), claims);

        //7.封装LoginVo对象（令牌和昵称） 常规创建封装对象
//        LoginVo loginVo = new LoginVo();
//        loginVo.setNickName(member.getName());
//        loginVo.setToken(token);
        //8.返回loginVo 建造者设计模式创建对象
        return LoginVo.builder()
                .token(token)
                .nickName(member.getName())
                .build();
    }

    @Override
    public PageResponse<NursingProjectVo> userNursingPaginationQuery(String name, Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        Page<NursingProjectVo> page = nursingProjectMapper.nursingPaginationQuery(name,status);

        PageResponse<NursingProjectVo> objectPageResponse = new PageResponse<>();
        objectPageResponse.setRecords(page.getResult());
        return objectPageResponse;
    }

    @Override
    public NursingProjectVo searchUserNursingProjectById(Integer id) {
        NursingProjectVo nursingProjectVo = nursingProjectMapper.searchNursingProjectById(Long.valueOf(id));
        return nursingProjectVo;
    }

    /**
     * 新增预约
     * @param
     * @return
     */
    @Override
    public void addAppointment(Visit visit) {
        visit.setStatus(0);
        visit.setCreateBy(UserThreadLocal.getUserId());
        customerUserMapper.addAppointment(visit);
    }

    /**
     * 分页查询预约
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResponse<VisitVo> pageQueryReservation(Integer pageNum, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNum,pageSize);
        Page<VisitVo> page=customerUserMapper.pageQueryReservation(status);
        PageResponse<VisitVo> objectPageResponse = new PageResponse<>();
        objectPageResponse.setRecords(page.getResult());
        return objectPageResponse;
    }

    /**
     * 取消预约
     * @param id
     * @return
     */
    @Override
    public void cancelReservation(Long id) {
        customerUserMapper.cancelReservation(id);
    }



    /**
     * 查询每个时间段剩余预约次数
     * @param localDateTime
     * @return
     */
    @Override
    public List<TimeCountVo> remainingReservationTimes(LocalDateTime localDateTime) {
        Integer total=6;
        List<TimeCountVo> timeCountVo=customerUserMapper.remainingReservationTimes(localDateTime);
        for (TimeCountVo countVo : timeCountVo) {
            Integer count = countVo.getCount();
            Integer end = total - count;
            countVo.setCount(end);
        }
        return timeCountVo;
    }

    /**
     * 查询取消预约数量
     * @return
     */
    @Override
    public Integer queryTheNumberOfCancelledAppointments(Long id) {
        return customerUserMapper.queryTheNumberOfCancelledAppointments(id);
    }

    @Scheduled(cron = "0 1,31 * * * ?")
    public void timer(){
        customerUserMapper.addTimer();
    }
}
